<template>
  <!---贷中新增-->
  <div class="monitoring-add">
    <div class="add-header">
      <div
        class="header-left"
        :class="selectAddType === 1 ? 'select-type' : ''"
        @click="addPannel(1)"
      >
        单笔添加
      </div>
      <div
        class="header-right"
        :class="selectAddType === 2 ? 'select-type' : ''"
        @click="addPannel(2)"
        v-if="permissionState.imports"
      >
        批量添加
      </div>
    </div>
    <div class="add-pannel">
      <div class="add-pannel-content" v-if="selectAddType == 1">
        <el-form
          ref="ruleFormRef"
          style="max-width: 700px; height: 100%"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
        >
          <div class="info-title"><span></span>基本信息</div>
          <el-form-item label="产品名称" prop="productName">
            <el-input v-model="ruleForm.productName" />
          </el-form-item>
          <el-form-item label="车辆所有人" prop="vehicleOwner">
            <el-select
              filterable
              allow-create
              v-model="ruleForm.vehicleOwner"
              placeholder="请选择"
              clearable
            >
              <el-option
                :label="org.orgName"
                :value="org.orgName"
                v-for="(org, index) in orgList"
                :key="index"
                :disabled="org.disabled"
                :change="selectOrg()"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="车辆抵押权人" prop="mortgagor">
            <el-select
              v-model="ruleForm.mortgagor"
              placeholder="请选择"
              clearable
            >
              <el-option
                :label="org.orgName"
                :value="org.orgName"
                v-for="(org, index) in orgList"
                :key="index"
                :disabled="org.disabled"
                :change="selectOrg()"
              />
            </el-select>
          </el-form-item>
          <div class="info-title">
            <span class="span"></span>申请人信息<span class="tip"
              >为保证监控质量，请务必完整准确填写申请人三要素信息。</span
            >
          </div>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>
          <el-form-item label="身份证号码" prop="cardId">
            <el-input v-model="ruleForm.cardId" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="ruleForm.phone" />
          </el-form-item>
          <el-form-item label="工作地址" prop="workAddress">
            <el-input v-model="ruleForm.workAddress" />
          </el-form-item>
          <el-form-item label="家庭地址" prop="homeAddress">
            <el-input v-model="ruleForm.homeAddress" />
          </el-form-item>
          <div class="info-title"><span class="span"></span>申请信息</div>
          <el-form-item label="申请时间" prop="applyDate">
            <el-date-picker
              v-model="ruleForm.applyDate"
              type="date"
              placeholder="请选择"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="交车时间">
            <el-date-picker
              v-model="ruleForm.deliveryDate"
              type="date"
              placeholder="请选择"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="首期还款时间">
            <el-date-picker
              v-model="ruleForm.firstRepaymentDate"
              type="date"
              placeholder="请选择"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-col :span="10">
              <el-form-item label="期数" prop="term">
                <el-input v-model="ruleForm.term" />
              </el-form-item>
            </el-col>
            <el-col :span="2"> 期 </el-col>
            <el-col :span="10">
              <el-form-item label="月租/月供" prop="monthlyRent">
                <el-input v-model="ruleForm.monthlyRent" />
              </el-form-item>
            </el-col>
            <el-col :span="2"> 元 </el-col>
          </el-form-item>

          <el-form-item>
            <el-col :span="10">
              <el-form-item label="融资方式" prop="financingMethod">
                <el-select
                  v-model="ruleForm.financingMethod"
                  placeholder="Select"
                  style="width: 240px"
                >
                  <el-option label="全融" :value="1" />
                  <el-option label="融车" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2"> </el-col>
            <el-col :span="10">
              <el-form-item label="押金" prop="depositRatio">
                <el-input v-model="ruleForm.depositRatio" />
              </el-form-item>
            </el-col>
            <el-col :span="2"> 元 </el-col>
          </el-form-item>
          <div class="info-title"><span class="span"></span>车辆基本信息</div>
          <el-form-item label="车牌号" prop="carPlate">
            <el-input v-model="ruleForm.carPlate" />
          </el-form-item>
          <el-form-item label="车架号" prop="vin">
            <el-input v-model="ruleForm.vin" />
          </el-form-item>
          <el-form-item label="品牌车型" prop="carModel">
            <el-input v-model="ruleForm.carModel" />
          </el-form-item>
          <el-form-item label="新车指导价" prop="newCarGuidePrice">
            <el-col :span="22">
              <el-input v-model="ruleForm.newCarGuidePrice" />
            </el-col>
            <el-col :span="2"> 元 </el-col>
          </el-form-item>
          <el-form-item>
            <el-col :span="10">
              <el-form-item label="裸车价（不包含税）" prop="transactionPrice">
                <el-input v-model="ruleForm.transactionPrice" />
              </el-form-item>
            </el-col>
            <el-col :span="2">元</el-col>
            <el-col :span="10">
              <el-form-item label="放款金额" prop="loanAmount">
                <el-input v-model="ruleForm.loanAmount" />
              </el-form-item>
            </el-col>
            <el-col :span="2">元</el-col>
          </el-form-item>
          <el-form-item>
            <el-col :span="10">
              <el-form-item label="已行驶里程" prop="mile">
                <el-input v-model="ruleForm.mile" />
              </el-form-item>
            </el-col>
            <el-col :span="2">公里</el-col>
            <el-col :span="12">
              <el-form-item label="初登日期" prop="regDate">
                <el-date-picker
                  v-model="ruleForm.regDate"
                  type="date"
                  placeholder="请选择"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="车辆所在城市" prop="selectCity">
            <el-cascader
              style="width: 100%"
              v-model="ruleForm.selectCity"
              :options="cityList"
              :show-all-levels="false"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="add-pannel-upload" v-if="selectAddType == 2">
        <el-upload
          class="upload-button"
          drag
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          limit="1"
          accept=".xlsx,.xls,.csv"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖拽至此或 <em>手动上传</em></div>
          <template #tip>
            <div class="el-upload__tip">
              <ul>
                <li>支持 2MB 以内的 xlsx、xls、csv 格式文件</li>
                <li>文件中数据不能超过 10000 行</li>
              </ul>
              <div class="export">
                <el-icon><UploadFilled /></el-icon>下载模板
              </div>
            </div>
          </template>
        </el-upload>
      </div>
      <div class="add-button">
        <el-button class="submit" @click="submitForm(ruleFormRef)">
          保存
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { UploadFilled } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import http from "@/request/request";
import { useRouter } from "vue-router"; // 引入useRouter函数
import { Permission } from "@/util/LocalStorgeGetPermission";
import { ElMessage, ElMessageBox } from "element-plus";

const router = useRouter(); // 获取路由实例
interface RuleForm {
  productName: string;
  vehicleOwner: string;
  name: string;
  cardId: string;
  phone: string;
  workAddress: string;
  homeAddress: string;
  applyDate: string;
  deliveryDate: string;
  firstRepaymentDate: string;
  term?: number;
  monthlyRent?: number;
  financingMethod: number;
  depositRatio?: number;
  carPlate: string;
  vin: string;
  carModel: string;
  newCarGuidePrice?: number;
  transactionPrice?: number;
  loanAmount?: number;
  mile?: number;
  regDate: string;
  cityId?: number;
  selectCity?: [string, number];
  mortgagor?: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  productName: "",
  name: "",
  cardId: "",
  phone: "",
  workAddress: "",
  homeAddress: "",
  applyDate: "",
  deliveryDate: "",
  firstRepaymentDate: "",
  financingMethod: 1,
  carPlate: "",
  vin: "",
  carModel: "",
  regDate: "",
  vehicleOwner: "",
});
interface CityList {
  label: string;
  value: string;
  children: CityList[];
}
interface Org {
  id: number;
  orgName: string;
  disabled: boolean;
}
const cityList = ref<CityList[]>([]);
const orgList = ref<Org[]>([]);
// 权限
const permissionState = ref({
  insert: false,
  update: false,
  delete: false,
  export: false,
  imports: false,
});
const selectAddType = ref(1); // 添加方式

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const checkNumber = (rule: any, value: any, callback: any) => {
  let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
  if (value === "") {
    callback(new Error("请输入内容"));
  } else if (!reg.test(value)) {
    callback(new Error("请输入数字"));
  } else if (value < 0 || value > 10000000) {
    callback(new Error("超出范围，请保持在0-1000万"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules<RuleForm>>({
  productName: [
    {
      required: true,
      message: "请输入产品",
      trigger: "blur",
    },
  ],
  name: [
    {
      required: false,
      pattern: /^[\u4e00-\u9fa5·]{2,15}$/,
      message: "只支持中文姓名",
      trigger: "blur",
    },
  ],
  cardId: [
    {
      required: false,
      pattern:
        /(^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/,
      message: "身份证号格式不正确",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      pattern:
        /^1(3[0-9]|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  applyDate: [
    {
      required: true,
      message: "请选择申请时间",
      trigger: "blur",
    },
  ],
  term: [
    {
      required: true,
      message: "请填写期数，1-72期",
      trigger: "blur",
    },
    {
      min: 1,
      max: 72,
      message: "请填写正确的期数，1-72期",
      trigger: "blur",
    },
  ],
  monthlyRent: [
    {
      required: true,
      message: "请填写月租/月供",
      trigger: "blur",
    },
  ],
  financingMethod: [
    {
      required: true,
      message: "请选择融资方式",
      trigger: "blur",
    },
  ],
  depositRatio: [{ required: true, message: "请填写押金", trigger: "blur" }],
  carPlate: [
    {
      required: false,
      pattern:
        /^(?:[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼][A-Z]|WJ[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]?)[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼][A-Z][DF][A-HJ-NP-Z0-9][0-9]{4}|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼][A-Z][0-9]{5}[DF]|使[0-9]{3}[0-9]{4}|领[0-9]{3}[0-9]{4}|粤Z[A-HJ-NP-Z0-9]{4}[港澳]$/,
      message: "请填写正确的车牌号",
      trigger: "blur",
    },
  ],
  vin: [
    {
      required: true,
      pattern: /^[A-HJ-NPR-Z0-9]{17}$/,
      message: "请填写正确的车架号",
      trigger: "blur",
    },
  ],
  carModel: [
    {
      required: true,
      message: "请填写押金",
      trigger: "blur",
    },
  ],
  newCarGuidePrice: [
    {
      required: true,
      message: "请填写新车指导价",
      trigger: "blur",
    },
    {
      validator: checkNumber,
      trigger: "blur",
    },
  ],
  transactionPrice: [
    {
      required: true,
      message: "请填写成交价",
      trigger: "blur",
    },
    {
      validator: checkNumber,
      trigger: "blur",
    },
  ],
  loanAmount: [
    {
      required: true,
      message: "请填写放款金额",
      trigger: "blur",
    },
    {
      validator: checkNumber,
      trigger: "blur",
    },
  ],
  mile: [
    {
      required: true,
      message: "请填写已行驶里程",
      trigger: "blur",
    },
    {
      validator: checkNumber,
      trigger: "blur",
    },
  ],
  regDate: [
    {
      required: true,
      message: "请填写初登日期",
      trigger: "blur",
    },
  ],
  selectCity: [
    {
      required: true,
      message: "请选择车辆所在城市",
      trigger: "blur",
    },
  ],
  vehicleOwner: [
    {
      required: true,
      message: "请填写车辆所有人",
      trigger: "blur",
    },
  ],
  mortgagor: [
    {
      required: true,
      message: "请填写车辆抵押权人",
      trigger: "blur",
    },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("请核对车辆所有人是否正确！", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          add();
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "取消保存",
          });
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const add = async () => {
  try {
    const { selectCity, ...params } = ruleForm;
    if (selectCity && selectCity.length >= 2) {
      params.cityId = selectCity[1];
    }

    await http.post("/api/after-loan/add", params);
    router.push("/monitoring");
  } catch (err) {
    console.log(err);
  }
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.push("/monitoring");
};

// 添加
const addPannel = (type: number) => {
  selectAddType.value = type;
};
// 查询城市列表
const getCityList = async () => {
  try {
    const { data } = await http.get<CityList[]>(
      "/api/other/getCityAndProv",
      ruleForm
    );
    cityList.value = data;
  } catch (err) {
    console.log(err);
  }
};
// 获取产权机构列表
const getPropertyOrgList = async () => {
  try {
    const { data } = await http.get<Org[]>(
      "/api/system/getSubOrgListByUserId",
      ruleForm
    );
    orgList.value = data;
    orgList.value.forEach((o) => {
      o.disabled = false;
    });
  } catch (err) {
    console.log(err);
  }
};
// 筛选机构
const selectOrg = () => {
  orgList.value.forEach((o) => {
    if (o.orgName === ruleForm.vehicleOwner) {
      o.disabled = true;
    } else if (o.orgName === ruleForm.mortgagor) {
      o.disabled = true;
    } else {
      o.disabled = false;
    }
  });
};

onMounted(() => {
  const p = new Permission("/monitoring").getPermission();
  if (!p) {
    router.push("/");
  } else {
    permissionState.value = p;
    getCityList();
    getPropertyOrgList();
  }
});
</script>

<style lang="less" scoped>
.monitoring-add {
  height: 100%;
  width: 100%;
  display: flex;
  background-color: rgb(255, 255, 255);
  .add-header {
    display: flex;
    justify-content: start;
    .header-left,
    .header-right {
      margin-top: 10px;
      width: 120px;
      height: 40px;
      line-height: 40px;
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
      background-color: rgb(242, 242, 242);
      margin-left: 20px;
      cursor: pointer;
    }
    .select-type {
      background-color: rgb(222, 41, 16);
      color: #fff;
    }
  }
  .add-pannel {
    padding-top: 50px;
    margin-left: 10%;
    width: 100%;
    height: 80%;
    display: flex;
    justify-content: start;
    .add-pannel-content {
      width: 100%;
      height: 65vh;
      overflow: auto;
      .info-title {
        display: flex;
        height: 16px;
        font-weight: 700;
        line-height: 16px;
        margin-bottom: 20px;
        .span {
          display: block;
          width: 2px;
          background-color: rgb(222, 41, 16);
          margin-right: 10px;
        }
        .tip {
          color: rgb(167, 169, 167);
          font-size: 14px;
          margin-left: 20px;
        }
      }
    }
    .add-pannel-content::-webkit-scrollbar {
      display: none; /* Safari and Chrome */
    }
    .add-pannel-upload {
      margin-top: 40px;
      margin-left: -40px;
      height: 100%;
      width: 70%;
      .upload-button {
        height: 80%;
      }

      .el-upload__tip {
        width: 300px;
        text-align: start;
        color: rgb(198, 198, 198);
        .export {
          font-size: 14px;
          color: rgb(222, 41, 16);
          cursor: pointer;
        }
      }
    }
  }
  .add-button {
    position: absolute;
    left: 65%;
    top: 87%;
    .el-button {
      width: 160px;
    }
    .submit {
      background-color: rgb(222, 41, 16);
      color: #fff;
    }
  }
}
::v-deep(.el-upload) {
  height: 80%;
}
::v-deep(.el-upload-dragger) {
  height: 100% !important;
  align-content: center !important;
}
</style>